import { useEffect, useState, useCallback } from "react";
import { useNavigate, useSearchParams } from "react-router";
import Box from "@mui/material/Box";
import TabContext from "@mui/lab/TabContext";
import TabPanel from "@mui/lab/TabPanel";
import Typography from "@mui/material/Typography";
import Fab from "@mui/material/Fab";
import AddIcon from "@mui/icons-material/Add";
import dayjs from "dayjs";

import ScheduleTabs from "../components/ScheduleTabs";
import RatingPage from "./schedule/RatingPage";
import CalendarPage from "./schedule/CalendarPage";
import ReportPage from "./schedule/ReportPage";
import AddProjectDialog from "../components/AddProjectDialog";

import {
  getAiReport,
  getScheduleItems,
  updateScheduleItems,
} from "../api/scheduleApi.js";
import { TrendingUpOutlined } from "@mui/icons-material";

// 常量定义
const TAB_INDICES = {
  RATING: "1",
  CALENDAR: "2",
  REPORT: "3",
};

function SchedulePage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // 状态管理 - 按功能分组
  const [activeTab, setActiveTab] = useState(TAB_INDICES.RATING);
  const [selectedDate, setSelectedDate] = useState(
    dayjs().format("YYYY-MM-DD")
  );
  const [scheduleData, setScheduleData] = useState({ id: null, date: null });
  const [projectEntries, setProjectEntries] = useState([]);
  const [isFirstLoad, setIsFirstLoad] = useState(true);

  // 报告相关状态
  const [aiReport, setAiReport] = useState("今日总结");
  const [hasAiReport, setHasAiReport] = useState(false);
  const [isGeneratingReport, setIsGeneratingReport] = useState(false);

  // 对话框状态
  const [showAddProjectDialog, setShowAddProjectDialog] = useState(false);

  // 数据加载 - 提取为独立函数
  const loadScheduleData = useCallback(async () => {
    try {
      const response = await getScheduleItems({ date: selectedDate });
      const data = response.data;
      const entries = JSON.parse(data.item || "[]");

      // 处理从计时器返回的数据
      const timerId = searchParams.get("id");
      const timerTime = searchParams.get("time");

      if (timerId && timerTime) {
        const targetItem = entries.find((item) => item.id === timerId);
        if (targetItem) {
          targetItem.time = timerTime;
          await updateScheduleItems({
            id: data.id,
            item: JSON.stringify(entries),
          });
          console.log("计时器数据更新成功");
        }
      }

      setProjectEntries(entries);
      setScheduleData(data);
      setHasAiReport(!!data.aiReport);
      setAiReport(data.aiReport || "");
      setActiveTab(TAB_INDICES.RATING);
      return entries; // 返回数据供后续使用
    } catch (error) {
      console.error("加载日程数据失败:", error);
      throw error; // 抛出错误供上层处理
    }
  }, [selectedDate, searchParams]);

  // 数据保存 - 提取为独立函数
  const saveProjectEntries = useCallback(async () => {
    if (isFirstLoad) return;

    try {
      await updateScheduleItems({
        id: scheduleData.id,
        item: JSON.stringify(projectEntries),
      });
      console.log("项目数据更新成功");
    } catch (error) {
      console.error("保存项目数据失败:", error);
    }
  }, [scheduleData.id, projectEntries, isFirstLoad]);

  // 事件处理函数 - 使用 useCallback 优化
  const handleTabChange = useCallback((event, newTab) => {
    setActiveTab(newTab);
  }, []);

  const handleDeleteProject = useCallback(async (projectId) => {
    setIsFirstLoad(false);
    setProjectEntries((prev) => prev.filter((entry) => entry.id !== projectId));
  }, []);

  const handleAddProject = useCallback(({ name, hasTime }) => {
    const newProject = {
      id: Date.now().toString(),
      name,
      rating: 0,
      hasTime,
      time: hasTime ? 0 : undefined,
    };

    setIsFirstLoad(false);
    setProjectEntries((prev) => [...prev, newProject]);
    setShowAddProjectDialog(false);
  }, []);

  const handleUpdateRating = useCallback((projectId, newRating) => {
    setIsFirstLoad(false);
    setProjectEntries((prev) =>
      prev.map((entry) =>
        entry.id === projectId ? { ...entry, rating: newRating } : entry
      )
    );
  }, []);

  const handleGenerateAiReport = useCallback(async () => {
    setIsGeneratingReport(true);
    try {
      const response = await getAiReport(scheduleData.date, null);
      if (response.code === 200) {
        setAiReport(response.data);
        setHasAiReport(true);
      }
    } catch (error) {
      console.error("生成AI报告失败:", error);
    } finally {
      setIsGeneratingReport(false);
    }
  }, [scheduleData.date]);

  const handleNavigateToTimer = useCallback(
    (project) => {
      if (project.hasTime) {
        navigate(`/timer?id=${project.id}&time=${project.time}`);
      }
    },
    [navigate]
  );

  // 日期变化监听
  // 修改日期变化监听，使其返回Promise
  const handleDateChange = useCallback((newDate) => {
    setSelectedDate(newDate);
  }, []);

  // 生命周期钩子
  useEffect(() => {
    saveProjectEntries();
  }, [saveProjectEntries]);

  useEffect(() => {
    loadScheduleData();
  }, [loadScheduleData]);

  return (
    <Box
      className="schedule-page"
      sx={{ height: "100%", display: "flex", flexDirection: "column" }}
    >
      <Typography
        variant="h4"
        sx={{
          fontFamily: '"Balsamiq Sans", cursive',
          fontWeight: 600,
          textAlign: "center",
          color: "text.primary",
          my: 3,
        }}
      >
        Daily Rate
      </Typography>

      <TabContext value={activeTab}>
        <ScheduleTabs value={activeTab} onChange={handleTabChange} />

        <TabPanel value={TAB_INDICES.RATING}>
          <RatingPage
            entries={projectEntries}
            onRatingChange={handleUpdateRating}
            onDelete={handleDeleteProject}
            showDelete={true}
            onNavTimer={handleNavigateToTimer}
          />

          <Fab
            color="primary"
            aria-label="add"
            onClick={() => setShowAddProjectDialog(true)}
            sx={{
              position: "fixed",
              bottom: 20,
              right: 20,
              boxShadow: "0 4px 20px rgba(0, 0, 0, 0.2)",
            }}
          >
            <AddIcon />
          </Fab>

          <AddProjectDialog
            open={showAddProjectDialog}
            onClose={() => setShowAddProjectDialog(false)}
            onAdd={handleAddProject}
          />
        </TabPanel>

        <TabPanel value={TAB_INDICES.CALENDAR} sx={{ padding: 0 }}>
          <CalendarPage
            onDateChange={handleDateChange}
            externalDate={selectedDate}
          />
        </TabPanel>

        <TabPanel value={TAB_INDICES.REPORT}>
          <ReportPage
            hasReport={hasAiReport}
            report={aiReport}
            isLoading={isGeneratingReport}
            onGenerateReport={handleGenerateAiReport}
            selectedDate={selectedDate}
          />
        </TabPanel>
      </TabContext>
    </Box>
  );
}

export default SchedulePage;
